﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Export.Web.Ui.pages
{
    public partial class login : System.Web.UI.Page
    {
        private DatabaseCore.UserDao _userProvider = new DatabaseCore.UserDao();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Page.IsPostBack)
            {
                string _username = username.Value;
                string _password = password.Value;

                if (!string.IsNullOrEmpty(_username) && !string.IsNullOrEmpty(_password))
                {
                    var userLogged = _userProvider.Login(_username, _password);
                    if (userLogged != null)
                    {
                        JavaScriptSerializer serializer = new JavaScriptSerializer();
                        FormsAuthentication.SetAuthCookie(userLogged.UserName, true);
                        Session["Username"] = userLogged.UserName;
                        Session["Role"] = userLogged.Role;
                        string userLoggedSerialized = serializer.Serialize(userLogged);
                        // Add the cookie to the request to save it
                        
                        HttpCookie cookie = new HttpCookie("exportCookie", userLoggedSerialized);
                        HttpContext.Current.Response.Cookies.Add(cookie);
                        switch (userLogged.Role)
                        {
                            case 2:
                                Response.Redirect("/pages/orderList.aspx");
                                break;
                            case 3:
                                Response.Redirect("/pages/approverOrderList.aspx");
                                break;
                            default:
                                Response.Redirect("/pages/orderList.aspx");
                                break;
                        }

                    }

                    else
                    {
                        logginError.Visible = true;
                    }
                }
            }
            else
            {
                var logout = HttpContext.Current.Request.QueryString["logout"];
                if (!string.IsNullOrEmpty(logout) && logout == "true")
                {
                    FormsAuthentication.SignOut();
                    //FormsAuthentication.RedirectToLoginPage();
                }
            }
        }
    }
}